package com.css.fxfzaqbz.base.user.repository.impl;

import com.css.fxfzaqbz.base.user.repository.UserRepository;
import com.css.fxfzaqbz.base.user.repository.entity.UserEntity;
import com.css.fxfzaqbz.base.user.viewobjects.UserQueryParams;
import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class UserRepositoryImpl implements UserRepository {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public UserEntity findOneByUserCodeAndIsValid(String userCode, String isValid) {
        String sql = "select * from sys_user where user_code = '"+ userCode +"' and is_valid = '"+ isValid +"'";
        try {
            UserEntity userEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(UserEntity.class));
            return userEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public UserEntity save(UserEntity userEntity) {
        String sql = "";
        if (PlatformObjectUtils.isNotEmpty(userEntity) && PlatformObjectUtils.isNotEmpty(userEntity.getUserId()) && PlatformObjectUtils.isNotEmpty(findByUserId(userEntity.getUserId()))){
            sql += "update sys_user set user_code = :userCode, user_name = :userName, sex = :sex, sort = :sort, birthday = :birthday, office_phone = :officePhone, mobile_phone = :mobilePhone " +
                    ", fax = :fax, email = :email, id_card = :idCard, extend1 = :extend1, extend2 = :extend2, is_valid = :isValid, create_user = :createUser, create_time = :createTime, update_user = :updateUser, update_time = :updateTime" +
                    "where user_id = '"+ userEntity.getUserId() +"'";
        }else {
            sql += "insert into sys_user values(:userId, :userCode, :userName, :sex, :sort, :birthday, :officePhone, :mobilePhone" +
                    ", :fax, :email, :idCard, :extend1, :extend2, :isValid, :createUser, :createTime, :updateUser, :updateTime) ";
        }

        SqlParameterSource source = new BeanPropertySqlParameterSource(userEntity);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int i = namedParameterJdbcTemplate.update(sql, source, keyHolder);
        return userEntity;
    }

    @Override
    public Page<UserEntity> getAllUserByParams(UserQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select distinct u.* from sys_user u ");

        StringBuilder orderSql = new StringBuilder(" order by u.sort");

        StringBuilder whereSql = new StringBuilder(" where u.is_valid = '" + YNEnum.Y.toString() + "'");

        if (!PlatformObjectUtils.isEmpty(queryParams.getUserName())) {
            whereSql.append(" and u.user_name like %" + queryParams.getUserName() + "%");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getUserCode())) {
            whereSql.append(" and u.user_code like %" + queryParams.getUserCode() + "%");
        }

        String wholeSql = sql.append(whereSql).append(orderSql).toString();
        List<UserEntity> list = jdbcTemplate.query(wholeSql, new BeanPropertyRowMapper<>(UserEntity.class));
        Pageable pageable = PageRequest.of(queryParams.getCurPage() - 1, queryParams.getPageSize());

        Page<UserEntity> users = new PageImpl<>(list, pageable, PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
        return users;
    }

    @Override
    public Map<String, Object> findUserBaseInfoVOByUserId(String userId) {
        String sql = "SELECT c.locked , u.*  FROM sys_user u LEFT JOIN sys_certification c ON u.user_id  = c.user_id WHERE u.user_id = '"+ userId + "'" ;
        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap(sql);
        return stringObjectMap;
    }

    @Override
    @Transactional
    public void deleteUsers(List<String> ids, String userId, Timestamp currentTimestamp) {
        String sql = "update sys_user set isValid = '" + YNEnum.N + "' ," +
                " update_user = '"+ userId +"' ," +
                " update_time = '"+ currentTimestamp +"' " +
                " where user_id in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    public UserEntity findByUserId(String userId){
        String sql = "select * from sys_user where user_id = '"+ userId +"'";
        try {
            UserEntity userEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(UserEntity.class));
            return userEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
}
